//
//  InspectViewController.m
//  Project6
//
//  Created by ToanDK on 11/13/12.
//  Copyright (c) 2012 DungNP. All rights reserved.
//

#import "InspectViewController.h"
#import "EnterDaveIDViewController.h"
#import "NewReportViewController.h"
#import "DamageReportViewController.h"
#import "QRDecodeResultViewController.h"

#import "DBProcessing.h"

@implementation InspectViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    // get suspend damage report records from plist data base
    suspendDamageReports =[[NSMutableArray alloc] initWithCapacity:0];
    //[self getDamageReportFromPlist:@"newreport.plist"];
    [self readAllNewreportsFromDB];
    
    if(tblInspectView) // not go from welcome screen
    {
        [tblInspectView reloadData];
    }
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    // set title and background image
    self.title =@"Inspect";
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"greyBackground"]];
    
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)btnScanQR_Click:(id)sender
{
    NSLog(@"btnScanQR_Click");
    [self scanQRcode];
    
}
-(void)scanQRcode
{
    ZBarReaderViewController *reader = [ZBarReaderViewController new];
    
    reader.readerDelegate = self;
    
    [reader.scanner setSymbology: 0
                          config: ZBAR_CFG_ENABLE
                              to: 0];
    [reader.scanner setSymbology: ZBAR_QRCODE
                          config: ZBAR_CFG_ENABLE
                              to: 1];
    reader.readerView.zoom = 1.0;
    [self presentModalViewController: reader
                            animated: YES];
}

- (void) imagePickerController: (UIImagePickerController*) reader
 didFinishPickingMediaWithInfo: (NSDictionary*) info
{
    id<NSFastEnumeration> results =
    [info objectForKey: ZBarReaderControllerResults];
    [info objectForKey: UIImagePickerControllerOriginalImage];
    
    ZBarSymbolSet *set = (ZBarSymbolSet *)results;
    NSString * data;
    for (ZBarSymbol *symbol in set)
    {
        NSLog(@"type: %@", symbol.typeName );
        NSLog(@"data: %@", symbol.data);
        data = symbol.data;
        break;
    }
    
    // dimiss scan QR
    [reader dismissModalViewControllerAnimated: YES];
    // Go to new report
    NewReportViewController *newReport =[[NewReportViewController alloc] initWithNibName:@"NewReportViewController" bundle:nil];
    // get dave ID string
    NSArray * separatedQRString = [data componentsSeparatedByString:@"|"];
    if (separatedQRString.count< 5) {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"QRScan" message:@"QRCode is invalid!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
    else
    {
        newReport.FARM_ID = separatedQRString[1];
        newReport.WTG_ID = separatedQRString[2];
        newReport.VIS_ID = separatedQRString[3];
        newReport.DIS_LENGTH = separatedQRString[4];
        
        [self.navigationController pushViewController:newReport animated:YES];
    }
    
}

#pragma mark - When Finish Shoot

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissModalViewControllerAnimated:YES];
}

-(IBAction)btnEnterDaveID:(id)sender
{
    NSLog(@"btnEnterDaveID");
    // go to enter dave ID screen
    EnterDaveIDViewController *enterDaveCtr = [[EnterDaveIDViewController alloc] initWithNibName:@"EnterDaveIDViewController" bundle:nil];
    [self.navigationController pushViewController:enterDaveCtr animated:YES];
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Only one section.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // return number of suspend damage reports
    return suspendDamageReports.count;
}

// show header of section
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"Continue reports";
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	NSString *CellIdentifier = [NSString stringWithFormat:@"ReportCell%d-%d", indexPath.section, indexPath.row];
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(cell ==nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    if(suspendDamageReports.count >0)
    {
        // Get the object to display and set the value in the cell.
        NSMutableDictionary * dic = (NSMutableDictionary*)[suspendDamageReports objectAtIndex:indexPath.row];
        NSString * wfidString =  (NSString *)[dic  objectForKey:@"wfid"];
        NSString * wtgidString = (NSString *)[dic  objectForKey:@"wtgid"];
        NSString * wtgvisidString = (NSString*)[dic objectForKey:@"wtgvisid"];
        NSString * bladeString = (NSString *)[dic  objectForKey:@"blade"];
        cell.textLabel.text =[wfidString stringByAppendingFormat:@"-%@-%@",wtgidString,wtgvisidString];
        cell.detailTextLabel.text =bladeString;
    }
    return cell;
}

- (UITableViewCellAccessoryType)tableView:(UITableView *)tv accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellAccessoryDisclosureIndicator;
}
//for sweping to delete row
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
           editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSUInteger row = [indexPath row];
    NSUInteger count = [suspendDamageReports count];
    
    if (row < count) {
        NSDictionary *report = suspendDamageReports[row];
        NSString *reportID = [report objectForKey:@"id"];
        [self deleteSuspendRecordsOnDBByNewreportID:reportID];
        [suspendDamageReports removeObjectAtIndex:row];

    }
}
- (void)tableView:(UITableView *)tableView
didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tblInspectView reloadData];
}

//End of delete row
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // go to damage reprot to cotinue report
    DamageReportViewController * damageCtroller = [[DamageReportViewController alloc] initWithNibName:@"DamageReportViewController" bundle:nil];
    
    // get newreport info
    damageCtroller.SuspendDicInfo = [suspendDamageReports objectAtIndex:indexPath.row];
    NSString * newreportidparent = [damageCtroller.SuspendDicInfo objectForKey:@"id"];
    
    // get saved damage report
    //NSMutableArray * damages = [self getDamagesFromPlist:@"damagereport.plist"];
    //NSMutableArray * suspendedDamages = [self getSavedDamageRecords:damages newReportID:newreportidparent];
    // change to use database
    NSMutableArray * suspendedDamages = [self getDamagesFromDBByNewreportID:newreportidparent];
    
    // assign suspend of saved damage records from db
    damageCtroller.suspendedDamageRecords = suspendedDamages;
    // go to damage report screen
    [self.navigationController pushViewController:damageCtroller animated:YES];
}


#pragma DB access processing

//----------------- CODE USE SQLITE--------------------------------------------------------------------
// get DB path
-(NSString *) getDatabasePath
{
    // get document path
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    // appending database name path
    NSString *databasePath = [documentsPath stringByAppendingPathComponent:kDataBaseName];
    
    return databasePath;
}
// read all newreports from DB
-(void) readAllNewreportsFromDB
{
    NSString * databasePath = [self getDatabasePath];
    suspendDamageReports = [DBProcessing readAllNewReports:databasePath];
}

// get damage records by newreportid
-(NSMutableArray *) getDamagesFromDBByNewreportID:(NSString *) newreportid
{
    NSString * databasePath = [self getDatabasePath];
   NSMutableArray * damages =  [DBProcessing readAllDamageReportsByNewreportID:newreportid onDatabase:databasePath];
    
    return damages;
}
-(void) deleteSuspendRecordsOnDBByNewreportID:(NSString *) newreportID
{
    // get database path
    NSString *databasePath = [self getDatabasePath];
    NSLog(@"databasePath:%@",databasePath);
    // delete newreport
    [DBProcessing deleteNewreportById:newreportID OnDB:databasePath];
    // delete damage records
    [DBProcessing deleteDamageReportByNewreportId:newreportID OnDB:databasePath];
}

//----------------------- CODE USE PLIST -------------------------------------------------------------
// get newreport table records
-(void) getDamageReportFromPlist:(NSString*) filePath
{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *damagePath = [documentsDirectory stringByAppendingPathComponent:filePath];
    
	NSFileManager *fileManager = [NSFileManager defaultManager];
	
	BOOL success = [fileManager fileExistsAtPath:damagePath];
    NSLog(@"damagePath:%@",damagePath);
    if (success) {
        suspendDamageReports = [NSMutableArray arrayWithContentsOfFile:damagePath];
    }
    
}

// get damage report table records
-(NSMutableArray *) getDamagesFromPlist:(NSString*) filePath
{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *damagePath = [documentsDirectory stringByAppendingPathComponent:filePath];
    
	NSFileManager *fileManager = [NSFileManager defaultManager];
	
	BOOL success = [fileManager fileExistsAtPath:damagePath];
    NSMutableArray * damages = [[NSMutableArray alloc] initWithCapacity:0];
    if (success) {
        damages = [NSMutableArray arrayWithContentsOfFile:damagePath];
    }
    
    return damages;
}

//get saved damage report from damagereport.plist have same newreport id
-(NSMutableArray *) getSavedDamageRecords:(NSMutableArray *) damages newReportID:(NSString *) newreportidparent
{
    NSMutableArray * rv = [[NSMutableArray alloc] initWithCapacity:0];
    
    for (int i=0; i<damages.count; i++)
    {
        
        NSMutableDictionary * damage = (NSMutableDictionary *)[damages objectAtIndex:i];
        
        NSString * newreportidchild = [damage objectForKey:@"newreportid"];
        if ([newreportidchild isEqualToString:newreportidparent])
        {
            [rv addObject:damage];
        }
    }
    
    return rv;
}


@end
